package com.kfm.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@WebFilter(urlPatterns = "/msg")
public class MsgFilter implements Filter {

    private List<String> wordList = new ArrayList<>();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        ServletContext servletContext = filterConfig.getServletContext();

        String realPath = servletContext.getRealPath("words.txt");

        File file = new File(realPath);

        try (BufferedReader br = new BufferedReader(new FileReader(file, StandardCharsets.UTF_8))){
            String word = null;
            while( (word = br.readLine()) != null){
                wordList.add(word);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(wordList);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        String msg = servletRequest.getParameter("msg");

        if (wordList.contains(msg)){
            msg = msg.replaceAll("\\D{1}", "*");
        }

        servletRequest.setAttribute("msg", msg);
        filterChain.doFilter(servletRequest, servletResponse);
    }

}
